package com.atguigu.day02;

import org.apache.flink.api.common.eventtime.*;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

// 自定义水位线发生器
public class Example1 {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        env
                .socketTextStream("localhost", 9999)
                .map(new MapFunction<String, Tuple2<String, Long>>() {
                    @Override
                    public Tuple2<String, Long> map(String value) throws Exception {
                        String[] arr = value.split(" ");
                        return Tuple2.of(arr[0], Long.parseLong(arr[1]) * 1000L);
                    }
                })
                .assignTimestampsAndWatermarks(
                        new WatermarkStrategy<Tuple2<String, Long>>() {
                            @Override
                            public TimestampAssigner<Tuple2<String, Long>> createTimestampAssigner(TimestampAssignerSupplier.Context context) {
                                return new SerializableTimestampAssigner<Tuple2<String, Long>>() {
                                    @Override
                                    public long extractTimestamp(Tuple2<String, Long> element, long recordTimestamp) {
                                        return element.f1; // 告诉flink，时间戳是哪个字段
                                    }
                                };
                            }

                            @Override
                            public WatermarkGenerator<Tuple2<String, Long>> createWatermarkGenerator(WatermarkGeneratorSupplier.Context context) {
                                return new WatermarkGenerator<Tuple2<String, Long>>() {
                                    private long bound = 5000L; // 最大延迟时间是5秒钟
                                    // 为了防止溢出，加上bound+1
                                    private long maxTs = Long.MIN_VALUE + bound + 1L;
                                    @Override
                                    public void onEvent(Tuple2<String, Long> event, long eventTimestamp, WatermarkOutput output) {
                                        // onEvent：每来一条数据触发一次执行
                                        // 更新观察到的最大事件时间戳
                                        maxTs = Math.max(maxTs, event.f1);
                                        // 这里也可以向下游发送水位线
                                        output.emitWatermark(new Watermark(
                                                maxTs - bound - 1L
                                        ));
                                    }

                                    @Override
                                    public void onPeriodicEmit(WatermarkOutput output) {
                                        // 默认每隔200毫秒的机器时间触发执行一次
                                        output.emitWatermark(new Watermark(
                                                maxTs - bound - 1L // 实现了默认公式
                                        ));
                                    }
                                };
                            }
                        }
                )
                .process(new ProcessFunction<Tuple2<String, Long>, String>() {
                    @Override
                    public void processElement(Tuple2<String, Long> value, Context ctx, Collector<String> out) throws Exception {
                        out.collect("到达的数据是：" + value + "，当前水位线是：" + ctx.timerService().currentWatermark());
                    }
                })
                .print();

        env.execute();
    }
}
